#!/bin/bash
#pMusic - functions without NLS
#GPL - Copyright Sigmund Berglund

export LC_ALL=C

case "$1" in
-bpm)
	#does it exist in DB
	IFS='|' read C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 BPM C <<< "$(grep -Fm1 "${2}|" "$STORAGE_DIR/index_mymusic")"
	if [ ! "$BPM" ]; then
		if type soundstretch > /dev/null 2>&1; then
			ffmpeg -i "$2" -ss 60 -t 60 -ar 32000 -ac 1 -f wav -y $WORKDIR/test.wav 2>/dev/null
			soundstretch $WORKDIR/test.wav -bpm 2> $WORKDIR/tmp_bpm
			BPM="`grep -F Detected $WORKDIR/tmp_bpm | cut -d' ' -f4 | cut -d. -f1`"
			#save to db
			( flock -e 202
				grep -aF "$2" "$STORAGE_DIR/index_mymusic" | awk -F'|' -v VAR1="$BPM" '{print $1 "|" $2 "|" $3 "|" $4 "|" $5 "|" $6 "|" $7 "|" $8 "|" $9 "|" $10 "|" $11 "|" $12 "|" VAR1 "|" $14 "|" $15 "|" $16 "|" $17 "|" $18 "|" $19 "|" $20 "|" $21}' >> $WORKDIR/mymusic_stack
			) 200>$WORKDIR/mymusic_stack.lockfile 
		fi
	fi
	#output to stdout
	echo $BPM
	;;

-sec2time) #transform 100 sec to 01:40
	MIN=$(($2/60))
	SEC=$(($2-($MIN*60)))
	echo $(printf "%02d" $MIN):$(printf "%02d" $SEC)
	;;

esac
